﻿using Zo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Zo.Config;
using Zo.Logging;

namespace BSAppDOne.WebAdmin.Custom
{
    /// <summary>
    /// 全局错误筛选器,用于捕捉错误及提示(当throw时触发)
    /// </summary>
    /// 
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class ErrorExceptionFilter : HandleErrorAttribute
    {

        public bool _IsExecute { get; set; }
        public override void OnException(ExceptionContext filterContext)
        {
            //正在发生错误
            if (_IsExecute)
            {
                ExceptionWeb(filterContext);
            }
                
            base.OnException(filterContext);
        }
        public ErrorExceptionFilter(bool isExecute)
        {
            this._IsExecute = isExecute;
        }

        private void ExceptionWeb(ExceptionContext filterContext)
        {
            var isAjax = filterContext.HttpContext.Request.IsAjaxRequest();
            if(filterContext.Exception is ErrorBox)
            {
                filterContext.HttpContext.Response.StatusCode = 200;//成功处理了请求
                var errorModel = ErrorModel.Instance;
                //只是拦截一些ajax类的方法
                if(isAjax)
                {
                    if(errorModel.status==(int)ErrorMsgStatus.Custom)
                    {
                        filterContext.Result = new JsonResult() { Data = errorModel.Data };
                    }
                    else
                    {
                        filterContext.Result = new JsonResult() { Data = errorModel };
                    }
                }
                else
                {
                    errorModel = new ErrorModel(filterContext.Exception.Message);
                    var _Script = $"<script type='text/javascript'>alert('{errorModel.msg.Trim()}')</script>";
                    filterContext.Result = new ContentResult() { Content = _Script, ContentType = "text/html;charset=utf-8;" };
                }

            }
            else
            {
                //记录错误信息
                LoggerFactory.Current.Create().LogInfo(filterContext.Exception.Message + filterContext.Exception.StackTrace, null);
                ErrorModel em = new ErrorModel(filterContext.Exception.Message);
                if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                {
                    //返回错误信息
                    filterContext.Result = new JsonResult() { Data = em };

                }
                else
                {
                    filterContext.Result = new ViewResult() { ViewName = AppConfig.ErrorPageUrl, ViewData = new ViewDataDictionary<ErrorModel>(em) };
                }
            }
            //表示异常已处理
            filterContext.ExceptionHandled = true;
        }
    }
}